package com.wing.order.service;

import com.wing.order.dao.DynamicDao;
import com.wing.order.model.response.EnterpriseVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DynamicServiceImpl implements DynamicService {

    @Autowired
    private DynamicDao dynamicDao;

    @Override
    public String getNextCode(String tableName) {
        Integer maxNo=dynamicDao.getMaxNo(tableName);
        return getCode(maxNo);
    }

    @Override
    public String getDayNextCode(String tableName) {

        Integer maxNo=dynamicDao.getDayMaxNo(tableName);
        return getCode(maxNo);
    }

    @Override
    public String getEnterpriseId() {
        return dynamicDao.getEnterpriseId();
    }

    @Override
    public String getEnterpriseName() {
        return dynamicDao.getEnterpriseName();
    }

    @Override
    public String getEnterpriseCode() {
        return dynamicDao.getEnterpriseCode();
    }

    @Override
    public EnterpriseVO getEnterprise() {
        return dynamicDao.getEnterprise();
    }

    @Override
    public String getDayMaxCode(String code, String tableName) {
        String maxNo = dynamicDao.getDayMaxCode(code, tableName);
        return getNewCode(maxNo);
    }

    @Override
    public String getMaxCode(String code, String tableName) {
        String maxNo = dynamicDao.getDayMaxCode(code, tableName);
        return getNewCode(maxNo);
    }

    private String getCode(Integer maxNo){
        String code="";
        if (maxNo==null){
            maxNo=1;
        }else{
            maxNo+=1;
        }
        return StringUtils.leftPad(maxNo.toString(),4,"0");
    }

    private String getNewCode(String maxNo){
        Integer newCode = 1;
        if (StringUtils.isNotBlank(maxNo)){
            newCode = Integer.parseInt(maxNo.substring(maxNo.length()-4)) + 1;
        }
        return StringUtils.leftPad(newCode.toString(),4,"0");
    }
}
